<template>
    <div class="tag-container">
        <!-- 查询表单 -->
        <div class="query-form-container">
            <el-form :inline="true" :model="queryInputModel" label-width="80px">
                <el-form-item label="编码:" prop="code">
                    <el-input v-model="queryInputModel.confident.code" placeholder="编码" clearable
                        style="width: 150px"></el-input>
                </el-form-item>
                <el-form-item label="名称:" prop="name">
                    <el-input v-model="queryInputModel.confident.name" placeholder="名称" clearable
                        style="width: 150px"></el-input>
                </el-form-item>

                <el-form-item label="是否启用:" prop="status">
                    <dictselection v-model="queryInputModel.confident.status" clearable style="width: 150px"
                        classCode="system:Status" :dictData="statsDic">
                    </dictselection>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" icon="Search" @click="refreshHandler">查询</el-button>
                    <el-button icon="Delete" @click="resetQueryInputHandler">清空</el-button>
                </el-form-item>
            </el-form>
        </div>


        <!-- 数据表格 -->
        <div class="table-container">
            <!-- 操作按钮 -->
            <div class="action-button-container">
                <el-row :gutter="5">
                    <el-col :span="1.5">
                        <el-button size="small" icon="Refresh" type="primary" plain
                            @click="refreshHandler">刷新</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button size="small" icon="Plus" type="primary" plain @click="addHandler">新增</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button size="small" icon="Download" type="warning" plain>导出</el-button>
                    </el-col>
                </el-row>
            </div>

            <el-table :data="postPaggerData.data" row-key="id" border style="width: 100%">
                <!-- 自动生成序号列 -->
                <el-table-column type="index" label="序号" width="60" align="center"></el-table-column>
                <el-table-column prop="code" label="编码" width="180" align="center" :show-overflow-tooltip="true"></el-table-column>
                <el-table-column prop="name" label="名称" width="150" :show-overflow-tooltip="true"></el-table-column>
                <el-table-column prop="sort" label="排序" width="120" align="center" :show-overflow-tooltip="true"></el-table-column>
                <el-table-column prop="status" label="状态" width="80" align="center" :show-overflow-tooltip="true">
                    <template #default="{ row }">
                        <el-switch v-model="row.status" :active-value="1" :inactive-value="0"
                            @change="setStatus(row)"></el-switch>
                    </template>
                </el-table-column>
                <el-table-column prop="createdAt" label="创建时间" align="center" width="180"
                    :show-overflow-tooltip="true"></el-table-column>
                <el-table-column prop="createdBy" label="创建人" align="center" width="120"
                    :show-overflow-tooltip="true"></el-table-column>
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button link size="small" type="primary" icon="Edit" @click="editHandler(scope.row)">编辑</el-button>
                        <el-popconfirm title="是否删除?" @confirm="delHandler(scope.row)">
                            <template #reference>
                                <el-button link size="small" type="danger" icon="Delete"
                                    @click="deleteHandler(scope.row)">删除</el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>

            <el-pagination layout="prev, pager, next" size="small" style="margin-top:10px"
                :total="postPaggerData.pageCount || 0" :page-sizes="[10, 20, 30, 40]" :pager-count="5"
                :background="true" v-model:current-page="queryInputModel.pageIndex"
                v-model:page-size="queryInputModel.pageSize" @change="loadData">
            </el-pagination>
        </div>
        <!-- 新增/编辑对话框 -->
        <el-dialog width="500" v-model="form.open" :title="form.title" append-to-body center>
            <el-form ref="formRef" :model="form.data" :rules="form.rules" label-width="auto">
                <el-form-item label="编码" prop="code">
                    <el-input v-model="form.data.code"></el-input>
                </el-form-item>
                <el-form-item label="名称" prop="name">
                    <el-input v-model="form.data.name"></el-input>
                </el-form-item>
                <el-form-item label="排序" prop="sort">
                    <el-input-number v-model="form.data.sort" :min="0"></el-input-number>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <dictselection v-model="form.data.status" classCode="system:Status" :dictData="statsDic">
                    </dictselection>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="form.open = false">取消</el-button>
                <el-button type="primary" @click="submitForm">保存</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import dictselection from '@/components/DictExtend/DictSelectionWithData.vue';
import msgHelper from '@/util/msgHelper.js'
import postApi from '@/api/system/post.js' // 替换为实际的 API 文件
import dictApi from "@/api/system/dict.js"
import dictTag from '@/components/DictExtend/DictDataTagForTableItem.vue';

const postPaggerData = ref({});
const queryInputModel = ref(
    {
        pageIndex: 1,
        pageSize: 10,
        confident: {
            code: undefined,
            name: undefined,
            status: null
        }
    }
); // 查询条件
const statsDic = ref([]);

const form = ref({
    open: false,
    title: '新增',
    data: {
        id: undefined,
        code: '',
        name: '',
        sort: 0,
        status: 1,
    },
    rules: {
        code: [{ required: true, message: '请输入编码', trigger: 'blur' }],
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        sort: [{ required: true, message: '请输入排序', trigger: 'blur' }],
    },
});

// 加载数据
const loadData = async () => {
    try {
        const res = await postApi.listPager(queryInputModel.value);
        postPaggerData.value = res.data.data;
    } catch (error) {
        msgHelper.showError('加载数据失败');
    }
};

// 刷新数据
const refreshHandler = () => {
    loadData();
};

// 清空查询条件
const resetQueryInputHandler = () => {
    queryInputModel.value =
    {
        pageIndex: 1,
        pageSize: 10,
        confident: {
            code: undefined,
            name: undefined,
            status: null
        }
    };
};

// 新增
const addHandler = () => {
    resetForm();
    form.value.title = "新增";
    form.value.open = true;
};

// 重置表单
const resetForm = () => {
    form.value.data = {
        id: undefined,
        code: '',
        name: '',
        sort: 0,
        status: 1,
    };
};

// 编辑
const editHandler = (row) => {
    resetForm();
    postApi.getById({ id: row.id }).then(res => {
        if (res.data.success) {
            form.value.data = res.data.data;
            form.value.open = true;
            form.value.title = "编辑";
        } else {
            msgHelper.show("获取数据失败" + res.data.msg);
        }
    });
};

// 删除
const deleteHandler = async (row) => {
    try {
        await postApi.del({ id: row.id, version: row.version });
        msgHelper.show('删除成功');
        loadData();
    } catch (error) {
        msgHelper.showError('删除失败');
    }
};

// 提交表单
const submitForm = async () => {
    if (form.value.data.id) {
        await postApi.update(form.value.data);
        msgHelper.show('更新成功');
    } else {
        await postApi.add(form.value.data);
        msgHelper.show('新增成功');
    }
    form.value.open = false;
    loadData();
};

onMounted(async () => {
    const Sres = await dictApi.getDataByCode("System:Status");
    if (Sres.data && Sres.data.data) {
        statsDic.value = Sres.data.data;
    }
});

const setStatus = async (row) => {
    await postApi
        .setStatus({ id: row.id, status: row.status, version: row.version })
        .then(res => {
            if (res.data.success) {
                msgHelper.show('更新成功');
                loadData();
            }
            else {
                msgHelper.showError('更新失败');
            }
        })
        .catch(error => {
            msgHelper.showError('更新失败');
        });

}
</script>

<style scoped></style>